<?php

Class Lib_CallCenter_YiChao_Main
{

    private static $url = ''; //请求地址
    private static $admin = ''; //管理员账号
    private static $pass = ''; //管理员密码
    private static $userName = ''; //坐席账号
    private static $passWord = ''; //坐席密码
    private static $company_code = ''; //公司名称


    public function __construct()
    {
        $env = getenv('RUNTIME_ENVIROMENT') ? getenv('RUNTIME_ENVIROMENT') : (defined('SHELL_VARIABLE') ? SHELL_VARIABLE : '');
        $env = empty($env) ? 'local' : $env;
        $config = require(LIBRARY_DIR . '/Conf/' . $env . '/callCenter.php');
        if (!isset($config)) {
            throw new Exception('can not found the callCenter env:' . $env . ' $config empty');
        }
        self::$url = $config["YiChao"]['url'];
        self::$userName = $config["YiChao"]['userName'];
        self::$passWord = $config["YiChao"]['passWord'];
        self::$pass = $config["YiChao"]['pass'];
    }

    /**
     * 获取请求url参数
     */
    private static function getUrlParam()
    {
        return  [
            'userName'=> self::$userName,
            'passWord'=> self::$passWord,
        ];
    }

    /*
     * GET请求接口
     */
    public function Grequest($action, $data = [], $timeout = 20 ,$nocheck = 0)
    {
        //初始化实例变量
        $params = array_merge(self::getUrlParam() , $data);
        //请求地址
        $ssid = str_replace('.','',uniqid('',true));
        $logs = ' ssid='.$ssid;
        $params['ssid'] = $ssid;
        //请求接口
        $result = Lib_CallCenter_YiChao_Curl::get(self::$url.$action , $params, $timeout, $nocheck);
        if($nocheck){
          return $result;
        }
         //初始化返回值
        $res = array('code' => 200, 'message' => 'success', 'data' => array());
        $res['ssid'] = $ssid;
        $logs .= ' request='.json_encode($params);
        $logs .= ' response='.json_encode($result);
        //连接错误
        if ($result['errno'] !== 200) {
            $res['data'] = $params;
            $res['message'] = '连接失败';
            Func_Log::write('callCenter_YiChao','WARNING',$logs.' link failure');
            return $res;
        }
        unset($result['errno']);
        if(!empty($result['uniquid'])){
            $logs .= ' uniquid='.$result['uniquid'];
        }
        if (isset($result['status']) && ($result['status'] == false || $result['status'] !=200 )){
            $res['code'] = 400;
            $res['message'] = $result['msg'];
            Func_Log::write('callCenter_YiChao','WARNING',$logs.' return error');
            return $res;
        }
        Func_Log::write('callCenter_YiChao','success',$logs.' request success');
        $res['data'] = $result;
        return $res;
    }

}

